<template>
  <div class="payment-page">
    <!-- 支付信息 -->
    <div class="payment-header">
      <h2>订单支付</h2>
      <div class="order-info">
        <span>订单号: {{ payment?.orderNumber || '--' }}</span>
        <span class="order-amount">¥{{ payment?.amount.toFixed(2) || '0.00' }}</span>
      </div>
    </div>

    <!-- 支付方式选择 -->
    <div class="payment-methods" v-if="!payment">
      <div class="section-title">选择支付方式</div>
      <div class="methods-grid">
        <div
          v-for="method in paymentMethods"
          :key="method.id"
          class="method-card"
          @click="selectPayment(method.id)"
        >
          <div class="method-icon" :class="method.icon">
            <van-icon :name="method.icon" size="24" />
          </div>
          <span class="method-name">{{ method.name }}</span>
        </div>
      </div>
    </div>

    <!-- 微信支付 -->
    <div v-if="payment && payment.method === 'wechat'" class="payment-content">
      <div class="wechat-payment">
        <div class="status-card">
          <div class="status-indicator">
            <van-loading v-if="isPaymentProcessing" size="24px" color="#1989fa" vertical>
              <div class="status-text">
                {{ statusText }}
              </div>
              <div class="status-time">等待时间: {{ waitTime }}秒</div>
            </van-loading>

            <div v-else-if="payment.status === 'success'" class="success-status">
              <van-icon name="checked" size="40" color="#07c160" />
              <p>支付成功</p>
            </div>

            <div v-else-if="payment.status === 'failed'" class="failed-status">
              <van-icon name="close" size="40" color="#ee0a24" />
              <p>支付失败</p>
            </div>
          </div>

          <p class="hint">正在前往微信支付，请稍候...</p>
        </div>

        <div class="qr-placeholder">
          <img src="../assets/wechat-qr-placeholder.jpg" alt="微信支付二维码" />
          <div class="qr-overlay" v-if="payment.status !== 'pending'">
            <div v-if="payment.status === 'processing'" class="processing-overlay">
              <van-loading type="spinner" color="white" />
              <p>支付处理中</p>
            </div>
            <div v-else-if="payment.status === 'success'" class="success-overlay">
              <p>支付成功</p>
            </div>
            <div v-else class="failed-overlay">
              <p>支付失败</p>
            </div>
          </div>
        </div>

        <p class="note">请使用微信扫描上方二维码完成支付</p>

        <van-button
          v-if="payment.status === 'failed'"
          round
          type="primary"
          block
          class="retry-button"
          @click="retryPayment"
        >
          重新支付
        </van-button>
      </div>
    </div>

    <!-- 余额支付 -->
    <div v-if="payment && payment.method === 'balance'" class="payment-content">
      <div class="balance-payment">
        <div class="balance-info">
          <div class="balance-label">账户余额</div>
          <div class="balance-amount">¥{{ userBalance.toFixed(2) }}</div>
        </div>

        <div class="payment-form">
          <!-- <van-password-input
            v-if="!paymentCompleted"
            v-model="password"
            :length="6"
            :mask="false"
            @input="handleInput"
            :gutter="5"
            :focused="showKeyboard"
          /> -->
          <!-- <van-password-input

            v-model="password"

            :mask="false"
            @input="handleInput"
            :gutter="5"

          /> -->
          <van-password-input
            :value="password"
            @input="handleInput"
            :mask="false"
            :gutter="5"
          />
          <!-- <p>当前密码：{{ password }}</p> -->

          <div v-if="paymentCompleted" class="payment-status">
            <div v-if="payment.status === 'success'" class="status-success">
              <van-icon name="checked" size="40" color="#07c160" />
              <p>支付成功</p>
            </div>
            <div v-else class="status-fail">
              <van-icon name="close" size="40" color="#ee0a24" />
              <p v-if="errorMessage">{{ errorMessage }}</p>
              <p v-else>支付失败</p>
            </div>
          </div>

          <van-number-keyboard
            v-if="showKeyboard && !paymentCompleted"
            v-model="password"
            :show="showKeyboard"
            theme="custom"
            extra-key="."
            close-button-text="完成"
            @blur="showKeyboard = false"
            @input="onInput"
          />
        </div>

        <div class="password-hint">
          <span v-if="passwordError" class="error">{{ passwordError }}</span>
          <span v-else>请输入6位支付密码</span>
        </div>

        <div class="action-buttons">
          <van-button
            v-if="!paymentCompleted"
            type="default"
            class="cancel-button"
            @click="cancelPayment"
          >
            取消支付
          </van-button>
          <van-button
            v-if="!paymentCompleted"
            type="primary"
            class="confirm-button"
            :disabled="password.length < 6 || loading"
            :loading="loading"
            @click="confirmBalancePayment"
          >
            确认支付
          </van-button>
          <van-button v-else type="primary" class="retry-button" @click="resetBalancePayment">
            {{ payment.status === 'success' ? '查看订单' : '重新支付' }}
          </van-button>
        </div>
      </div>
    </div>

    <!-- 二维码支付 -->
    <div v-if="payment && payment.method === 'qr'" class="payment-content">
      <div class="qr-payment">
        <div class="status-card">
          <div class="status-indicator">
            <van-loading v-if="isPaymentProcessing" size="24px" color="#1989fa" vertical>
              <div class="status-text">
                {{ statusText }}
              </div>
            </van-loading>

            <div v-else-if="payment.status === 'success'" class="success-status">
              <van-icon name="checked" size="40" color="#07c160" />
              <p>支付成功</p>
            </div>

            <div v-else-if="payment.status === 'failed'" class="failed-status">
              <van-icon name="close" size="40" color="#ee0a24" />
              <p>支付失败</p>
            </div>
          </div>

          <p class="hint" v-if="isPaymentProcessing">{{ paymentMethodInfo.name }}支付码有效时间:</p>
          <div class="countdown" v-if="isPaymentProcessing">
            <van-circle
              v-model:current-rate="countdownProgress"
              :rate="100"
              :speed="100"
              color="#1989fa"
              size="60px"
              layer-color="#eee"
              :stroke-width="60"
              :text="countdownText"
            />
          </div>
        </div>

        <div class="qr-container">
          <div class="qr-code">
            <img v-if="qrCodeUrl" :src="qrCodeUrl" alt="支付二维码" />
            <div class="qr-overlay" v-if="payment.status !== 'pending'">
              <div v-if="payment.status === 'processing'" class="processing-overlay">
                <van-loading type="spinner" color="white" />
                <p>支付处理中</p>
              </div>
              <div v-else-if="payment.status === 'success'" class="success-overlay">
                <p>支付成功</p>
              </div>
              <div v-else class="failed-overlay">
                <p>支付失败</p>
              </div>
            </div>
          </div>
          <p class="qr-hint">请使用{{ paymentMethodInfo.name }}扫码支付</p>
        </div>

        <div class="action-buttons">
          <van-button type="default" class="cancel-button" @click="cancelPayment">
            取消支付
          </van-button>
          <van-button
            type="primary"
            class="change-method"
            v-if="payment.status !== 'success'"
            @click="changePaymentMethod"
          >
            更换支付方式
          </van-button>
        </div>
      </div>
    </div>

    <!-- 支付结果弹窗 -->
    <van-dialog
      v-model:show="showSuccessDialog"
      title="支付成功"
      confirmButtonText="查看订单"
      @confirm="toOrderDetail"
    >
      <div class="dialog-content">
        <van-icon name="checked" size="60" color="#07c160" />
        <p>支付金额: ¥{{ payment?.amount.toFixed(2) }}</p>
        <p>订单号: {{ payment?.orderNumber }}</p>
      </div>
    </van-dialog>

    <van-dialog
      v-model:show="showFailedDialog"
      title="支付失败"
      confirmButtonText="重新支付"
      cancelButtonText="更换方式"
      @confirm="retryPayment"
      @cancel="changePaymentMethod"
    >
      <div class="dialog-content">
        <van-icon name="close" size="60" color="#ee0a24" />
        <p v-if="errorMessage">{{ errorMessage }}</p>
        <p>订单号: {{ payment?.orderNumber }}</p>
      </div>
    </van-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import { useUserStore } from '../stores/user'
import PaymentService from '../services/paymentService'
import type { PaymentInfo, PaymentMethod } from '../types/payment'

export default defineComponent({
  name: 'PaymentPage',
  setup() {
    const router = useRouter()
    const userStore = useUserStore()

    // 当前支付信息
    const payment = ref<PaymentInfo | null>(null)

    // 支付方式
    const paymentMethods = ref([
      { id: 'wechat', name: '微信支付', icon: 'wechat' },
      { id: 'balance', name: '余额支付', icon: 'balance-pay' },
      { id: 'qr', name: '扫码支付', icon: 'qr' },
      { id: 'alipay', name: '支付宝', icon: 'alipay' },
    ])

    // 余额支付相关
    const password = ref('')
    const showKeyboard = ref(true)
    const loading = ref(false)
    const paymentCompleted = ref(false)
    const passwordError = ref('')
    const errorMessage = ref('')

    // 支付状态
    const showSuccessDialog = ref(false)
    const showFailedDialog = ref(false)
    const countdownProgress = ref(100)
    const countdownValue = ref(0)

    // 用户余额
    const userBalance = computed(() => userStore.userInfo?.balance || 0)

    // 当前支付方式信息
    const paymentMethodInfo = computed(() => {
      if (!payment.value) return paymentMethods.value[0]
      return (
        paymentMethods.value.find((m) => m.id === payment.value!.method) || paymentMethods.value[0]
      )
    })

    // 是否正在处理支付
    const isPaymentProcessing = computed(() => {
      return payment.value
        ? payment.value.status === 'pending' || payment.value.status === 'processing'
        : false
    })

    // 支付状态文本
    const statusText = computed(() => {
      if (!payment.value) return ''
      switch (payment.value.status) {
        case 'pending':
          return '正在发起支付'
        case 'processing':
          return '支付处理中'
        default:
          return ''
      }
    })

    // 等待时间计算
    const waitTime = ref(0)

    // 倒计时文本
    const countdownText = computed(() => {
      const min = Math.floor(countdownValue.value / 60)
      const sec = countdownValue.value % 60
      return `${min}:${sec < 10 ? '0' + sec : sec}`
    })

    // 二维码URL
    const qrCodeUrl = computed(() => {
      if (!payment.value || payment.value.method !== 'qr') return ''
      return (payment.value as any).qrData?.qrCode || ''
    })

    // 倒计时处理
    let countdownTimer: number | null = null

    const startCountdown = (seconds: number) => {
      countdownValue.value = seconds

      if (countdownTimer) {
        clearInterval(countdownTimer)
      }

      countdownTimer = setInterval(() => {
        if (countdownValue.value > 0) {
          countdownValue.value--
          countdownProgress.value = (countdownValue.value / seconds) * 100
        } else {
          if (countdownTimer) {
            clearInterval(countdownTimer)
            countdownTimer = null
          }
        }
      }, 1000)
    }

    // 选择支付方式
    const selectPayment = (method: PaymentMethod) => {
      if (!userStore.isLoggedIn) {
        Toast('请先登录')
        router.push('/login')
        return
      }

      // 模拟订单ID和金额
      const orderId = `order_${Date.now()}`
      const amount = 125.5 // 实际应从订单获取

      PaymentService.createPayment(orderId, amount, method)
        .then((paymentInfo) => {
          payment.value = paymentInfo

          // 如果是二维码支付，开始倒计时
          if (method === 'qr') {
            startCountdown(300) // 5分钟倒计时
          } else if (method === 'wechat') {
            // 开始计时等待
            startCountdown(0) // 只用于显示，微信不显示倒计时
          }
        })
        .catch((error) => {
          console.error('创建支付失败:', error)
          Toast('创建支付失败')
        })
    }

    const onInput = (key) => {
      console.log(password, 'fffffffffffff', key)
    }
    const handleInput = (value) => {
      console.log(password, 'fffffffffffff', value)
      password.value = value
    }

    // 确认余额支付
    const confirmBalancePayment = async () => {
      if (!payment.value) return
      console.log('gggggggggggggggggg', password)
      if (password.value.length < 6) {
        passwordError.value = '请输入完整的6位密码'
        return
      }

      loading.value = true
      passwordError.value = ''
      errorMessage.value = ''

      try {
        const status = await PaymentService.payWithBalance({
          amount: payment.value.amount,
          password: password.value,
        })

        paymentCompleted.value = true

        if (status === 'success') {
          payment.value.status = 'success'
          showSuccessDialog.value = true
        } else {
          payment.value.status = 'failed'
          errorMessage.value = '支付失败，请检查密码或余额'
          showFailedDialog.value = true
        }
      } catch (error) {
        payment.value.status = 'failed'
        paymentCompleted.value = true
        errorMessage.value = '支付处理错误，请重试'
        showFailedDialog.value = true
      } finally {
        loading.value = false
      }
    }

    // 重置余额支付
    const resetBalancePayment = () => {
      password.value = ''
      passwordError.value = ''
      errorMessage.value = ''
      paymentCompleted.value = false
      showKeyboard.value = true

      if (payment.value && payment.value.status === 'success') {
        toOrderDetail()
      }
    }

    // 重新支付
    const retryPayment = () => {
      if (!payment.value) return

      PaymentService.createPayment(
        payment.value.orderId,
        payment.value.amount,
        payment.value.method,
      )
        .then((paymentInfo) => {
          payment.value = paymentInfo
          showSuccessDialog.value = false
          showFailedDialog.value = false

          if (payment.value?.method === 'qr') {
            startCountdown(300)
          }
        })
        .catch((error) => {
          console.error('重新支付失败:', error)
          Toast('重新支付失败')
        })
    }

    // 更换支付方式
    const changePaymentMethod = () => {
      payment.value = null
      showSuccessDialog.value = false
      showFailedDialog.value = false
    }

    // 取消支付
    const cancelPayment = () => {
      payment.value = null
      router.go(-1)
    }

    // 查看订单详情
    const toOrderDetail = () => {
      if (payment.value) {
        router.push({
          name: 'OrderDetail',
          params: { id: payment.value.orderId },
        })
      }
    }

    // 订阅支付状态更新
    let unsubscribe: (() => void) | null = null

    onMounted(() => {
      unsubscribe = PaymentService.subscribe((updatedPayment) => {
        payment.value = updatedPayment

        if (updatedPayment.status === 'success') {
          if (updatedPayment.method === 'qr' || updatedPayment.method === 'wechat') {
            showSuccessDialog.value = true
          }
        } else if (updatedPayment.status === 'failed') {
          if (updatedPayment.method === 'qr' || updatedPayment.method === 'wechat') {
            showFailedDialog.value = true
            errorMessage.value = '支付失败，请重试'
          }
        }
      })

      // 初始化当前支付
      payment.value = PaymentService.getCurrentPayment().value
    })

    onUnmounted(() => {
      if (unsubscribe) {
        unsubscribe()
      }
    })

    return {
      payment,
      paymentMethods,
      userBalance,
      password,
      showKeyboard,
      loading,
      paymentCompleted,
      passwordError,
      errorMessage,
      isPaymentProcessing,
      statusText,
      waitTime,
      countdownProgress,
      countdownText,
      qrCodeUrl,
      showSuccessDialog,
      showFailedDialog,
      paymentMethodInfo,
      onInput,
      handleInput,
      selectPayment,
      confirmBalancePayment,
      resetBalancePayment,
      retryPayment,
      changePaymentMethod,
      cancelPayment,
      toOrderDetail,
    }
  },
})
</script>

<style lang="scss" scoped>
.payment-page {
  padding: 16px;
  min-height: 100vh;
  background-color: #f7f9fb;

  .payment-header {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-bottom: 16px;

    h2 {
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 20px;
      color: #333;
    }

    .order-info {
      display: flex;
      justify-content: space-between;
      font-size: 15px;
      color: #666;

      .order-amount {
        font-weight: bold;
        color: #ee0a24;
        font-size: 18px;
      }
    }
  }

  .payment-methods {
    background: white;
    border-radius: 12px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-bottom: 16px;
      padding-left: 8px;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background: #1989fa;
        border-radius: 2px;
      }
    }

    .methods-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;

      .method-card {
        background: #f7f9fb;
        border-radius: 8px;
        padding: 20px 10px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
          background: white;
        }

        .method-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          margin: 0 auto 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 0;

          &.wechat {
            background: #07c160;
          }

          &.balance-pay {
            background: #1989fa;
          }

          &.qr {
            background: #ff9800;
          }

          &.alipay {
            background: #1890ff;
          }

          .van-icon {
            color: white;
          }
        }

        .method-name {
          font-size: 15px;
          color: #333;
        }
      }
    }
  }

  .payment-content {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .status-card {
      text-align: center;
      padding: 15px 0;

      .status-indicator {
        min-height: 120px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .success-status {
        p {
          font-size: 16px;
          color: #07c160;
          margin-top: 8px;
          font-weight: bold;
        }
      }

      .failed-status {
        p {
          font-size: 16px;
          color: #ee0a24;
          margin-top: 8px;
          font-weight: bold;
        }
      }

      .hint {
        font-size: 14px;
        color: #666;
        margin: 8px 0;
      }

      .countdown {
        margin: 15px auto;
        display: inline-block;
      }
    }

    // 微信支付样式
    .wechat-payment {
      .qr-placeholder {
        position: relative;
        width: 200px;
        height: 200px;
        margin: 0 auto;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .qr-overlay {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: rgba(0, 0, 0, 0.6);
          display: flex;
          align-items: center;
          justify-content: center;

          .processing-overlay,
          .success-overlay,
          .failed-overlay {
            color: white;
            text-align: center;

            p {
              margin-top: 8px;
            }
          }

          .success-overlay {
            color: #07c160;
          }

          .failed-overlay {
            color: #ee0a24;
          }
        }
      }

      .note {
        text-align: center;
        font-size: 14px;
        color: #999;
        margin: 20px 0;
      }

      .retry-button {
        margin-top: 20px;
      }
    }

    // 余额支付样式
    .balance-payment {
      .balance-info {
        background: #f0f7ff;
        border-radius: 8px;
        padding: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .balance-label {
          font-size: 15px;
          color: #666;
        }

        .balance-amount {
          font-size: 20px;
          color: #1989fa;
          font-weight: bold;
        }
      }

      .payment-form {
        position: relative;
        margin-bottom: 30px;

        :deep(.van-password-input) {
          margin: 0 auto;
          width: 280px;
        }

        :deep(.van-password-input__security) {
          height: 44px;
        }

        :deep(.van-password-input__item) {
          background: #f7f8fa;
          font-size: 20px;
        }

        .payment-status {
          text-align: center;
          padding: 30px 0;

          .status-success p {
            color: #07c160;
            font-weight: bold;
          }

          .status-fail p {
            color: #ee0a24;
            font-weight: bold;
          }
        }
      }

      .password-hint {
        text-align: center;
        font-size: 14px;
        height: 20px;
        margin-bottom: 15px;

        .error {
          color: #ee0a24;
        }
      }

      .action-buttons {
        display: flex;
        gap: 15px;

        .van-button {
          flex: 1;
          border-radius: 20px;
        }
      }
    }

    // 二维码支付样式
    .qr-payment {
      .qr-container {
        margin: 20px auto;
        text-align: center;

        .qr-code {
          position: relative;
          width: 200px;
          height: 200px;
          margin: 0 auto;
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .qr-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            display: flex;
            align-items: center;
            justify-content: center;

            .processing-overlay,
            .success-overlay,
            .failed-overlay {
              color: white;
              text-align: center;

              p {
                margin-top: 8px;
              }
            }

            .success-overlay {
              color: #07c160;
            }

            .failed-overlay {
              color: #ee0a24;
            }
          }
        }

        .qr-hint {
          margin-top: 15px;
          font-size: 14px;
          color: #999;
        }
      }

      .action-buttons {
        display: flex;
        gap: 15px;
        margin-top: 20px;

        .van-button {
          flex: 1;
          border-radius: 20px;
        }
      }
    }
  }

  .dialog-content {
    text-align: center;
    padding: 20px;

    p {
      margin: 8px 0;
      font-size: 15px;
    }
  }
}
</style>
